package com.fengye.generate;


import com.fengye.generate.entity.TableNameInfo;
import com.fengye.generate.mapper.TableNamesMapper;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@MapperScan("com.fengye.generate.mapper")
@SpringBootApplication
public class Main implements CommandLineRunner {

	@Autowired
	private TableNamesMapper tableNamesMapper;

	@Autowired
	SqlSessionFactory sqlSessionFactory;

	public static void main(String[] args) {
		new SpringApplicationBuilder(Main.class).web(WebApplicationType.NONE).run(args);
	}

	@Override
	public void run(String... args) throws Exception {
		Configuration configuration = sqlSessionFactory.getConfiguration();
		String databaseId = configuration.getDatabaseId();
		System.out.println("databaseId = " + databaseId);
		String outputFile = "update_statements.sql";
		BufferedWriter writer = null;
		// 打开文件以写入SQL语句
		writer = new BufferedWriter(new FileWriter(outputFile));
		List<String> tableNames = tableNamesMapper.getTableNames();
		try {
			for (String tableName : tableNames) {
				TableNameInfo createTime = tableNamesMapper.getTableColumn(tableName, "create_time");
				if (createTime != null) {
					String alterCreateTimeSql = "ALTER TABLE `usercenter`.`" + tableName +
							"` MODIFY COLUMN `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间';\n";
					writer.write(alterCreateTimeSql);
				}
				TableNameInfo updateTime = tableNamesMapper.getTableColumn(tableName, "update_time");
				if (updateTime != null) {
					String alterUpdateTimeSql = "ALTER TABLE `usercenter`.`" + tableName +
							"` MODIFY COLUMN `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间';\n";
					writer.write(alterUpdateTimeSql);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
